﻿using UnityEngine;
using Zenject;

public class EnemyChaseAction : FSMActionMB
{
    private EnemyBase enemy;
    private Rigidbody2D rigidbody2D;
    [Inject] private GameManager _gameManager;

    private void Awake()
    {
        enemy = GetComponent<EnemyBase>();
        rigidbody2D = GetComponent<Rigidbody2D>();
    }

    public override void Act()
    {
        // 每帧判断
        if (_gameManager.currentPlayer == null ||
            _gameManager.currentPlayer.GetComponent<PlayerHealth>().isDead) return;
        ActMove();
        ActFlip();
    }

    private void ActMove()
    {
        // 目标
        Transform target = _gameManager.currentPlayer.transform;
        //利用rigidbody2d来移动
        rigidbody2D.MovePosition(Vector2.MoveTowards(transform.position, target.position,
            enemy.speed * Time.deltaTime));
    }

    private void ActFlip()
    {
        Transform target = _gameManager.currentPlayer.transform;
        if (transform.position.x > target.position.x && enemy.isFacingRight ||
            transform.position.x < target.position.x && !enemy.isFacingRight)
        {
            Flip();
        }
    }

    private void Flip()
    {
        transform.Rotate(0, 180, 0);
        enemy.isFacingRight = !enemy.isFacingRight;
    }


    public override void Reset()
    {
    }
}